package com.fuhe.chen.vendingmachine.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fuhe.chen.vendingmachine.alipay.AlipayUtil;
import com.fuhe.chen.vendingmachine.common.MachineCache;
import com.fuhe.chen.vendingmachine.dto.ApiResponse;
import com.fuhe.chen.vendingmachine.dto.ApiResponseForList;
import com.fuhe.chen.vendingmachine.constant.MessageConstant;
import com.fuhe.chen.vendingmachine.constant.WebConst;
import com.fuhe.chen.vendingmachine.pojo.BookOrder;
import com.fuhe.chen.vendingmachine.pojo.User;
import com.fuhe.chen.vendingmachine.service.IBookOrderService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

import static com.fuhe.chen.vendingmachine.constant.MessageConstant.BookOrder.APPLY_REFUND_BOOK_ORDER_SUCCESS;
import static com.fuhe.chen.vendingmachine.constant.MessageConstant.BookOrder.CANCEL_BOOK_ORDER_SUCCESS;

@Controller
@RequestMapping("/app/bookOrder")
@ResponseBody
@Api(tags = "预约订单接口(面向app)")
public class BookOrderController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BookOrderController.class);

    @Autowired
    IBookOrderService bookOrderService;

    @ApiOperation(value = "创建新预约订单", notes = "参数:用户id,价格,商品id数组,订单备注,机器id")
    @PostMapping("/createBookOrder")
    public ApiResponse<BookOrder> createBookOrder(@RequestParam("user_id") String user_id,
                                                  @RequestParam("amount") Float amount,
                                                  @RequestParam("machine_id") Integer machine_id,
                                                  String comment,
                                                  @RequestParam("commodities") String commodities,
                                                  HttpServletRequest request) {
        ApiResponse<BookOrder> response = new ApiResponse<>();

        //只有本人可以添加自己的订单
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        boolean isPermitted = userInfo.getId().equals(user_id);

        //检测取货柜是否还有剩余容量
        Integer capacity = MachineCache.getCapacity(machine_id);
        if(capacity!=null&&capacity<=0){
            response.setSuccess(false);
            response.setCode(53333);
            response.setMessage("非常抱歉,本机器已经没有剩余容量存放订单货物,请选择其他取货柜");
            return response;
        }

        if (isPermitted) {
            List<JSONObject> commoditiesList = (List<JSONObject>) JSON.parse(commodities);
            BookOrder bookOrder = bookOrderService.addBookOrder(user_id, amount, machine_id, comment, commoditiesList);
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.CREATE_SUCCESS_MESSAGE);
            response.setData(bookOrder);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_ADD_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_ADD_PERMISSION_MESSAGE);
        }
        return response;
    }

    @ApiOperation(value = "取消预约订单")
    @PostMapping("/cancelBookOrder")
    public ApiResponse<String> cancelBookOrder(@RequestParam("user_id") String user_id,
                                               @RequestParam("book_order_id") String book_order_id,
                                               HttpServletRequest request) {
        ApiResponse<String> response = new ApiResponse<>();

        //只有本人可以取消自己的订单
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        boolean isPermitted = userInfo.getId().equals(user_id);

        if (isPermitted) {
            String result = bookOrderService.cancelBookOrder(book_order_id);
            if (result.equals(CANCEL_BOOK_ORDER_SUCCESS)) {
                response.setSuccess(true);
                response.setCode(MessageConstant.Success.SUCCESS_CODE);
                response.setMessage(MessageConstant.Success.DO_SUCCESS_MESSAGE);
            } else {
                response.setSuccess(false);
                response.setCode(MessageConstant.BookOrder.CANCEL_BOOK_ORDER_FAILURE_CODE);
                response.setMessage(MessageConstant.BookOrder.CANCEL_BOOK_ORDER_FAILURE);
            }
            response.setData(result);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_DELETE_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_DELETE_PERMISSION_MESSAGE);
        }
        return response;
    }

    @ApiOperation(value = "申请订单退款")
    @PostMapping("/applyForRefundBookOrder")
    public ApiResponse<String> applyForRefundBookOrder(@RequestParam("bookOrderId") String bookOrderId,
                                                       @RequestParam("refund_reason") String refund_reason,
                                                       @RequestParam("user_id") String user_id,
                                                       HttpServletRequest request) {

        ApiResponse<String> response = new ApiResponse<>();

        //只有本人可以申请自己的订单退款
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        boolean isPermitted = userInfo.getId().equals(user_id);

        if (isPermitted) {
            String result = bookOrderService.applyForRefundBookOrder(bookOrderId, refund_reason);
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.DO_SUCCESS_MESSAGE);
            response.setData(result);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_DO_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_DO_PERMISSION_MESSAGE);
        }
        return response;
    }

    @ApiOperation(value = "取消申请订单退款")
    @PostMapping("/cancelRefundBookOrder")
    public ApiResponse<String> cancelRefundBookOrder(@RequestParam("bookOrderId") String bookOrderId,
                                                     @RequestParam("user_id") String user_id,
                                                     HttpServletRequest request) {

        ApiResponse<String> response = new ApiResponse<>();

        //只有本人可以申请自己的取消订单退款
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        boolean isPermitted = userInfo.getId().equals(user_id);

        if (isPermitted) {
            String result = bookOrderService.cancelRefundBookOrder(bookOrderId);
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.DO_SUCCESS_MESSAGE);
            response.setData(result);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_DO_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_DO_PERMISSION_MESSAGE);
        }
        return response;
    }

    @ApiOperation(value = "获取支付宝sign")
    @PostMapping("/getSign")
    public ApiResponse<String> getSign(String jsonParams) {
        Map<String, String> map = (Map<String, String>) JSON.parse(jsonParams);

        String sign = AlipayUtil.getSign(map);
        ApiResponse<String> response = new ApiResponse<>();
        response.setSuccess(true);
        response.setCode(MessageConstant.Success.SUCCESS_CODE);
        response.setMessage(MessageConstant.Success.CREATE_SUCCESS_MESSAGE);
        response.setData(sign);
        return response;
    }

    @ApiOperation(value = "查询用户订单列表", notes = "参数:用户id,订单状态,页数")
    @PostMapping("/getBookOrderList")
    public ApiResponseForList<BookOrder> getBookOrderList(@RequestParam("user_id") String user_id,
                                                          @RequestParam(name = "status", required = false) Integer status,
                                                          @RequestParam("pageNum") Integer pageNum,
                                                          @RequestParam(name = "orderId", required = false) String orderId,
                                                          HttpServletRequest request
    ) {
        ApiResponseForList<BookOrder> response = new ApiResponseForList<>();

        //只有本人能查询自己的list,除非拥有管理权限
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        Subject subject = SecurityUtils.getSubject();
        boolean isPermitted = subject.isPermitted("admin") || userInfo.getId().equals(user_id);

        if (isPermitted) {
            PageInfo<BookOrder> bookOrderPageInfo = bookOrderService.queryOrderByUserId(user_id, status, orderId, pageNum, 10);
            response.setData(bookOrderPageInfo.getList());
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_QUERY_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_QUERY_PERMISSION_MESSAGE);
        }
        return response;
    }

    @ApiOperation(value = "查询订单详情", notes = "参数:订单id")
    @PostMapping("/getOrderDetail")
    public ApiResponse<BookOrder> getOrderDetail(@RequestParam("order_id") String order_id, HttpServletRequest request) {
        BookOrder bookOrder = bookOrderService.queryOrderByOrderId(order_id);
        ApiResponse<BookOrder> response = new ApiResponse<>();
        //只有本人能查询自己的order
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
        Subject subject = SecurityUtils.getSubject();
        boolean isPermitted = userInfo.getId().equals(bookOrder.getUser_id());

        if (isPermitted) {
            response.setSuccess(true);
            response.setCode(MessageConstant.Success.SUCCESS_CODE);
            response.setMessage(MessageConstant.Success.QUERY_SUCCESS_MESSAGE);
            response.setData(bookOrder);
        } else {
            response.setSuccess(false);
            response.setCode(MessageConstant.Error.NO_QUERY_PERMISSION_CODE);
            response.setMessage(MessageConstant.Error.NO_QUERY_PERMISSION_MESSAGE);
        }
        return response;
    }
}
